<?php

namespace App\Admin\Controllers;

use App\Models\Order;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Admin;
use App\Models\OrderRefund;
use Encore\Admin\Layout\Content;
use Encore\Admin\Controllers\AdminController;
use App\Services\AutoRefundProductOrder\AutoRefundProductOrder;

class OrderRefundsController extends AdminController
{
    protected $title = '订单售后管理';
	
	protected function refund($id = null)
	{
		if ($id and ($refund = OrderRefund::find($id))) {
			return $refund;
		}
		return null;
	}
    
    protected function grid()
    {
        $grid = new Grid(new OrderRefund());
        $grid->model()->latest();

        $grid->disableRowSelector();
        $grid->disableCreateButton();
        $grid->disableExport();
        
        $grid->column('id', 'ID');
        $grid->column('user_id', '会员')->display(function () {
	        return $this->user ? $this->user->nameText() : '';
        });
        $grid->column('order_id', '订单');
        $grid->column('order_item_id', '订单明细');
        $grid->column('refund_money', '退款');
        $grid->column('type', '售后类型');
        $grid->column('reason', '售后原因');
        $grid->column('parcel_status', '包裹状态');
        $grid->column('refund_status', '售后状态')->display(function ($value) {
	        return _label(Order::$refundStatus[$value], 'primary');
        });
        $grid->column('created_at', '申请时间')->display(function () {
	        return $this->created_at->toDatetimeString();
        });
        
        $this->gridActions($grid);

        return $grid;
    }
    
    protected function gridActions(Grid $grid)
    {
	    $grid->actions(function (Grid\Displayers\Actions $actions) {
	    	$actions->disableView();
	    	$actions->disableDelete();
	    });
    }
	
	public function edit($id, Content $content)
	{
		return $content
			->title($this->title())
			->description($this->description['edit'] ?? trans('admin.edit'))
			->body($this->form($id)->edit($id));
	}
	
	protected function form($id = null)
    {
    	$refund = $this->refund($id);
    	
        $form = new Form(new OrderRefund());
        
        $form->tab('售后申请', function ($form) use ($refund) {
	        $form->display('user.name', '会员');
	        $form->display('order_id', '订单')->with(function ($value) {
		        return 'ID: '.$value.' Number: '.$this->order->number;
	        });
	        $form->display('order_item_id', '明细');
	        $form->display('refund_money', '退款')->default(0.00);
	        $form->display('type', '售后类型');
	        $form->display('reason', '售后原因');
	        $form->display('parcel_status', '包裹状态')->value(111);
	        $this->formImages($form, $refund);
	
	        /*if ($refund and $refund->refund_status !== 'applied') {
		        $form->display('refund_status', '售后状态')->with(function ($value) {
			        return config("site.order.refund.status.{$value}");
		        });
	        } else {
		        $form->radio('refund_status', '售后状态')->options([
		        	'refused' => '拒绝售后',
			        'confirmed' => '审核通过'
		        ]);
	        }*/
	        
        })->tab('协商会话', function ($form) {
	        /**
	         * Negotiation with users.
	         */
        	$form->hasMany('orderrefundnegos', '会话', function (Form\NestedForm $form) {
        		$form->textarea('content', '内容');
        		 $form->radio('is_platform', '客服响应')->default(true)->options(config('site.bool'));
	        });
        });
        
        Admin::script("$('.form-group .remove').remove();");
        
        $this->formTools($form);
        $this->formFooter($form, $refund);
        $this->formSaved($form);
        $this->formSaved($form);
        
        return $form;
    }
    
    protected function formImages(Form $form, OrderRefund $refund = null)
    {
	    if ($refund and $refund->proof_images) {
		    foreach ($refund->proof_images as $image) {
			    if (isset($image['image'])) {
			    	$form->html(_form_image($image['image']), '图像证明');
			    }
		    }
	    }
    }
    
    protected function formTools(Form $form)
    {
	    $form->tools(function (Form\Tools $tools) {
	    	$tools->disableDelete();
	    	$tools->disableView();
	    });
    }
    
    protected function formFooter(Form $form, OrderRefund $refund = null)
    {
	    $form->footer(function (Form\Footer $footer) use ($refund) {
		
		    if ($refund and $refund->refund_status != 'applied') {
		    	$footer->disableSubmit();
		    }
	    	
	    	$footer->disableViewCheck();
	    	$footer->disableCreatingCheck();
	    	$footer->disableEditingCheck();
	    	$footer->disableReset();
	    });
    }
	
	protected function formSaving(Form $form)
	{
		$form->saving(function (Form $form) {
			
			$originalStatus = $form->model()->getOriginal('refund_status');
			
			Log::debug("OrderRefund original status: {$originalStatus}");
			Log::debug("OrderRefund current status: {$form->refund_status}");
			
			$status = $originalStatus;
			
			if ($originalStatus === 'applied' and $form->refund_status === 'refused') {
				$status = 'refused';
			}
			if ($originalStatus === 'applied' and $form->refund_status === 'confirmed') {
				$status = 'confirmed';
			}
			
			$form->refund_status = $status;
		});
	}
	
	protected function formSaved(Form $form)
	{
		$form->saved(function (Form $form) {
			$refund = $form->model();
			if ($refund->refund_status === 'refused') {
				app(AutoRefundProductOrder::class, ['refund' => $form->model()])->refuse();
			}
			if ($refund->refund_status === 'confirmed') {
				app(AutoRefundProductOrder::class, ['refund' => $form->model()])->refund();
			}
		});
	}
}
